
package com.ifcar.app.activity.topic;

import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;

import com.ifcar.app.activity.NewsPage;
import com.ifcar.app.adapter.VoteAdapter;
import com.ifcar.app.adapter.VoteViewBinder;
import com.ifcar.app.fragment.NRFragment;
import com.ifcar.app.model.Vote;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.view.HeadlineGallery;
import com.ifcar.app.activity.R;

public class VoteGalleryFrament extends NRFragment implements OnClickListener {

    public static final String TAG = "VoteGalleryFrament";

    public static final int MSG_DO_VOTE_SUCCESS = 0;

    public static final int MSG_DO_VOTE_FAILED = MSG_DO_VOTE_SUCCESS + 1;

    private HeadlineGallery mGallery;

    private VoteAdapter mAdapter;

    private List<Map<String, Object>> mData;

    private ProgressDialog mProgressDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.vote_layout, container, false);
    }

    @Override
    public void onViewCreatedNR(View view, Bundle savedInstanceState) {
        super.onViewCreatedNR(view, savedInstanceState);
        mGallery = (HeadlineGallery) view.findViewById(R.id.vote_grally);

        List<Map<String, Object>> data = getApplication().getVoteList();
        Bundle b = getArguments();
        int position = b.getInt("position", 0);

        setData(data, position);

    }

    @Override
    public void onTabSelected(boolean first) {
        super.onTabSelected(first);
        setTitle(R.string.vote_title);
    }

    private void setData(List<Map<String, Object>> data, int position) {
        if (data == null || data.size() == 0) {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            mGallery.setVisibility(View.GONE);
            return;
        }

        mData = data;

        mAdapter = new VoteAdapter(getActivity(), mData, this);
        mAdapter.setViewBinder(new VoteViewBinder(getActivity()));
        mGallery.setVisibility(View.VISIBLE);
        mGallery.setAdapter(mAdapter);
        if (position >= 0 && position < mAdapter.getCount()) {
            mGallery.getGallery().setSelection(position);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.vote_submit_button:
                doVote(v);
                break;
            case R.id.digest_container: {
                Map<String, Object> data = (Map<String, Object>) v.getTag();
                String docid = (String) ModelUtils.getValue(data, StringUtil.VOTE_DOCID);
                if (!TextUtils.isEmpty(docid)) {
                    Intent itemintent = new Intent(getActivity(), NewsPage.class);
                    Bundle b = new Bundle();
                    b.putString(GetColumnsInfo.DOCID_TAG, docid);
                    b.putString(GetColumnsInfo.TID_TAG, "");
                    b.putString("position", "0");
                    b.putBoolean(GetColumnsInfo.HEADLINE_TAG, false);
                    b.putBoolean("isCollect", true);
                    itemintent.putExtras(b);
                    startActivity(itemintent);
                }
                break;
            }
            default:
                break;
        }

    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_DO_VOTE_FAILED:
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    Toast.makeText(getActivity(), "对不起，投票失败！", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_DO_VOTE_SUCCESS:
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    doVoteSuccess((Map<String, Object>) msg.obj, msg.arg1);
                    break;
                default:
                    break;
            }
        }

    };

    private void doVote(View v) {
        final Map<String, Object> data = (Map<String, Object>) v.getTag(R.id.vote_submit);
        if (data == null) {
            return;
        }

        final String voteId = (String) ModelUtils.getValue(data, StringUtil.VOTE_ID);
        if (TextUtils.isEmpty(voteId)) {
            return;
        }

        List<Map<String, Object>> itemList = (List<Map<String, Object>>) ModelUtils.getValue(data,
                StringUtil.VOTE_ITEM_LIST);
        if (itemList == null) {
            return;
        }

        final Integer position = (Integer) v.getTag(R.id.vote_submit_button);
        if (position == null) {
            return;
        }

        final String itemId = position >= 0 && position < itemList.size() ? (String) ModelUtils
                .getValue(itemList.get(position), StringUtil.VOTE_ITEM_ID) : null;
        if (TextUtils.isEmpty(itemId)) {
            return;
        }

        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("提交投票数据...");
            mProgressDialog.setCancelable(true);
        }
        mProgressDialog.show();

        new Thread() {
            @Override
            public void run() {
                boolean success = Vote.doVote(getActivity(), getDb(), voteId, itemId);
                Message msg = mHandler.obtainMessage(success ? MSG_DO_VOTE_SUCCESS
                        : MSG_DO_VOTE_FAILED);
                msg.arg1 = position;
                msg.obj = data;
                mHandler.sendMessage(msg);
            }
        }.start();
    }

    private void doVoteSuccess(Map<String, Object> data, int position) {
        if (mData != getApplication().getVoteList()) {
            return;
        }
        data.put("startSeeAnimation", true);
        List<Map<String, Object>> itemList = (List<Map<String, Object>>) ModelUtils.getValue(data,
                StringUtil.VOTE_ITEM_LIST);

        Map<String, Object> itemData = itemList.get(position);

        int num = Vote.getVoteItemNum(itemData);
        itemData.put(StringUtil.VOTE_ITEM_NUM, String.valueOf(num + 1));
        itemData.put("startAddoneAnimation", true);

        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onApplyTheme() {
        super.onApplyTheme();

        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        Context context = getActivity();

        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
    }

}
